create procedure wp_GetCommonState
	@sourceState int,
	@targetState int
as
	declare @commonState int
	declare @sourceInfoState int
	declare @targetInfoState int
	declare @sourceBranchID int
	declare @targetBranchID int
	declare @sst int --source SourceState
	declare @tst int --target SourceState
	declare @tempstate int

	select @sourceInfoState = max(State) from Info
		where State <= @sourceState
	select @targetInfoState = max(State) from Info
		where State <= @targetState
	
	select @sourceBranchID = BranchID from Info
		where State = @sourceInfoState
	select @targetBranchID = BranchID from Info
		where State = @targetInfoState

	while isnull(@sourceBranchID, 0) <> isnull(@targetBranchID, 0)
	begin
		select @sst = null
		select @tst = null

		select @sst = SourceState from Branch
			where ID = @sourceBranchID
		select @tst = SourceState from Branch
			where ID = @targetBranchID
		if isnull(@tst, 0) >= isnull(@sst, 0)
		begin
			select @tempstate = max(State) from Info
				where State <= @tst
			select @targetBranchID = BranchID from Info
				where State = @tempstate
			if isnull(@targetBranchID, 0) = isnull(@sourceBranchID, 0)
			begin
				if @tst <= @sourceState
					select @commonState = @tst
				else
					select @commonState = @sourceState

				select @commonState
				return					
			end
			else
				select @targetState = @tst
		end
		else
		begin
			select @tempstate = max(State) from Info
				where State <= @sst
			select @sourceBranchID = BranchID from Info
				where State = @tempstate
			if isnull(@sourceBranchID, 0) = isnull(@targetBranchID, 0)
			begin
				if @sst <= @targetState
					select @commonState = @sst
				else
					select @commonState = @targetState

				select @commonState
				return					
			end
			else
				select @sourceState = @sst
		end
	end

	if @targetState <= @sourceState
		select @commonState = @targetState
	else
		select @commonState = @sourceState

	select @commonState